package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class GeoLocationToAddress {

    private static final String API_URL = "https://restapi.amap.com/v3/geocode/regeo";
    private static final String KEY = "7d3481adb0ca715c5f859dcfe496a6cd";

    public static final String PROVINCE = "province";
    public static final String CITY = "city";
    public static final String DISTRICT = "district";

    public static String getProvinceCityDistrict(double longitude, double latitude) {
        String parameters = "?key=" + KEY;
        parameters += "&location=" + longitude + "," + latitude;
        parameters += "&extensions=all";
        parameters += "&output=JSON";

        String urlString = API_URL + parameters;
        StringBuilder res = new StringBuilder();

        try {
            log.info("Amap API Request URL: " + urlString);
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                res.append(line);
            }
            in.close();

            log.info("Map API Response: " + res);

            JSONObject json = JSONObject.parseObject(res.toString());
            if ("1".equals(json.getString("status"))) {
                JSONObject regeocode = json.getJSONObject("regeocode");
                JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
                String province = addressComponent.getString("province");
                String city = addressComponent.getString("city");
                String district = addressComponent.getString("district");

                return "City:" + city + ", District:" + district;
            } else {
                log.info("Map API Response Error: " + json.getString("info"));
            }
        } catch (Exception e) {
            log.info("Error getting address information");
            e.printStackTrace();
        }
        return null;
    }


    public static Map<String, String> getProvinceCityDistrictMap(double longitude, double latitude) {
        Map<String, String> result = new HashMap<>();

        String parameters = "?key=" + KEY;
        parameters += "&location=" + longitude + "," + latitude;
        parameters += "&extensions=all";
        parameters += "&output=JSON";

        String urlString = API_URL + parameters;
        StringBuilder res = new StringBuilder();

        try {
            log.info("Amap API Request URL: " + urlString);
            URL url = new URL(urlString);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
            String line;
            while ((line = in.readLine()) != null) {
                res.append(line);
            }
            in.close();

            log.info("Map API Response: " + res);

            JSONObject json = JSONObject.parseObject(res.toString());
            if ("1".equals(json.getString("status"))) {
                JSONObject regeocode = json.getJSONObject("regeocode");
                JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
                String province = addressComponent.getString("province");
                String city = addressComponent.getString("city");
                String district = addressComponent.getString("district");
                result.put(PROVINCE, province);
                result.put(CITY, city);
                result.put(DISTRICT, district);
                return result;
            } else {
                log.info("Map API Response Error: " + json.getString("info"));
            }
        } catch (Exception e) {
            log.info("Error getting address information");
            e.printStackTrace();
        }
        return null;
    }
    public static void main(String[] args) {
        double longitude = 123.429441;
        double latitude = 41.83544;
        String addressInfo = getProvinceCityDistrict(longitude, latitude);
        Map<String, String> addressMap = getProvinceCityDistrictMap(longitude, latitude);
        System.out.println(addressInfo);
        System.out.println(addressMap);
    }
}
